/**
 * 
 */
package org.xserver.runtime.jetty.command;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * @author jkonopka
 * 
 */
public class ServerStopCommand extends AbstractServerCommand {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7111196044297142719L;

	/**
	 * 
	 */
	private static final String SERVER_ADDRESS = "server.address";

	/**
	 * 
	 */
	private static final String SERVER_STOP_PORT = "server.stop.port";

	/**
	 * @param properties {@link Properties}
	 */
	public ServerStopCommand(Properties properties) {
		super(properties);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jserver.command.ICommand#execute()
	 */
	@Override
	public void execute() throws Exception {

		final Socket socket = getSocket();
		if (socket != null) {

			final OutputStream out = socket.getOutputStream();
			if (out != null) {
				getLog().info("*** sending jetty stop request ***");
				out.write(("\r\n").getBytes());
				out.flush();
			}

			getLog().info(socket.toString());
			if (!socket.isClosed()) {
				socket.close();
			}
		}

	}

	/**
	 * @return {@link Socket}
	 * @throws IOException IO error handling
	 * @throws UnknownHostException unknown host error handling
	 */
	public Socket getSocket() throws IOException, UnknownHostException {
		return new Socket(getInetAddress(), getStopPort());
	}

	/**
	 * @return port number from application settings
	 */
	public Integer getStopPort() {
		return Integer.valueOf(getProperties().getProperty(SERVER_STOP_PORT));
	}

	/**
	 * @return {@link InetAddress}
	 * @throws UnknownHostException Errorhandling
	 */
	public InetAddress getInetAddress() throws UnknownHostException {
		return InetAddress.getByName(getProperties().getProperty(SERVER_ADDRESS));
	}
}
